package services

import (
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	"gowww/comeon/models"
	"time"
)

type Admin struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

//
//  Add
//  @Description: 登陆用户添加
//  @receiver admin
//  @return id
//  @return err
//
func (admin *Admin) Add() (id int, err error) {
	var adminModel models.Admin
	adminModel.Username = admin.Username
	data, err := adminModel.GetOne()
	if err == nil && data.Id > 0 {
		err = errors.New("用户名已存在")
		return
	}
	adminModel.Password = Md5(admin.Password)
	adminModel.CreatedAt = time.Now().Unix()
	adminModel.UpdatedAt = time.Now().Unix()
	id, err = adminModel.Add()
	return
}

//
//  Md5
//  @Description: 生成md5字符串
//  @param str
//  @return string
//
func Md5(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	md5Str := fmt.Sprintf("%x", has)
	return md5Str
}

//
//  Login
//  @Description: 登录
//  @receiver admin
//  @return data
//  @return err
//
func (admin *Admin) Login() (data interface{}, err error) {
	var adminModel = &models.Admin{
		Username: admin.Username,
		Password: admin.Password,
	}
	ret, err := adminModel.GetOne()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("用户不存在")
	}

	if ret.Password != Md5(admin.Password) {
		return nil, errors.New("密码错误")
	}
	if ret.Status == 0 {
		return nil, errors.New("当前用户已被禁用")
	}
	adminData := make(map[string]interface{})
	adminData["id"] = ret.Id
	adminData["username"] = ret.Username
	adminData["type"] = ret.Type
	return adminData, err
}
